package embyparse.noobparser;

import java.util.ArrayList;

import embyparse.parsetree.ParseNode;
/**
 * @author Justin
 *
 */
public class Pattern {



	String name;
	Pattern superPattern;
	Matcher m;
	int precedence;
	public Pattern(String name) {
		this(name, 0);
	}

	public Pattern(String name, int precedence){
		this.name = name;
		this.precedence = precedence;
	}

	public Pattern setSuperPattern(String name){
		int matchcount = 0;
		for(int i = 0; i<PatternDefinitions.ALL_PATTERNS.size();i++){
			if(name.equals(PatternDefinitions.ALL_PATTERNS.get(i).name)){
				superPattern = PatternDefinitions.ALL_PATTERNS.get(i);
				matchcount++;
			}
		}
		if(matchcount==0){
			new InternalError("No patterns named "+name);
		}
		if(matchcount>1){
			new InternalError("More than one pattern named "+name);
		}
		return this;
	}

	public Pattern add(){
		PatternDefinitions.ALL_PATTERNS.add(this);
		return this;
	}

	public void setMatcher(Matcher match){
		m=match;
	}

	/**
	 * Should not do ANYTHING, as normal patterns do not have anything to match.
	 * @param stack
	 * @param lookahead
	 * @return stack, unchanged
	 */
	public ArrayList<ParseNode> match(ArrayList<ParseNode> stack, ParseNode lookahead){
		//should not be used
		return stack;
	}

	/**
	 * Checks if this pattern's (and its superpatterns) are equal to the given tag.
	 * @param _tag
	 * @return true if _tag matches the tag or a supertag of this pattern
	 */
	public boolean equalTag(String _tag){
		Pattern tag = this;
		while( tag != null){//CHECK SUPERTAGS!!!
			//System.out.println("TAG NAME: "+tag.name+"@ index "+(stack.size()+(i-patterns.length))+" (pattern requires: "+patterns[i]+")");
			if (_tag.equals(tag.name)){
				//System.out.println("match!");
				return true;
			}
			tag = tag.superPattern;
		}
			//System.out.println("no match!");
			return false;
	}

	public String getName(){
		return name;
	}

	public String toString(){
		return "Pattern:"+name;
	}
}
